
@extends('dashboard.includes.master')
@section('title', 'Add Template')

@section('css')
    <link href="https://cdn.jsdelivr.net/npm/quill@2.0.3/dist/quill.snow.css" rel="stylesheet" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css">
    <style>
        #preview-container {
            border: 1px solid #ccc;
            padding: 15px;
            min-height: 200px;
            background: #fff;
            display: none;
        }
    </style>
@endsection

@section('content')
<div class="col-xl-12">
    <div class="row">
        <div class="col-xl-12">
            <div class="card custom-card">
                @if(session('success'))
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        {{ session('success') }}
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                @endif

                <div class="card-body">
                    <form action="{{ route('tempelete.store') }}" method="POST" enctype="multipart/form-data" id="mainForm">
                        @csrf
                        <div class="row gy-4">
                            <div class="mb-3 col-4">
                                <label for="subject" class="form-label">Subject</label>
                                <input class="form-control @error('subject') is-invalid @enderror" type="text" name="subject" placeholder="Subject" value="{{ old('subject') }}">
                                @error('subject')
                                    <span class="invalid-feedback">{{ $message }}</span>
                                @enderror
                            </div>
                            <div>
                                <textarea name="body" id="body" style="display: none;"></textarea>
                                <div id="toolbar-container">
                                    <span class="ql-formats">
                                        <select class="ql-font"></select>
                                        <select class="ql-size"></select>
                                    </span>
                                    <span class="ql-formats">
                                        <button class="ql-bold"></button>
                                        <button class="ql-italic"></button>
                                        <button class="ql-underline"></button>
                                        <button class="ql-strike"></button>
                                    </span>
                                    <span class="ql-formats">
                                        <select class="ql-color"></select>
                                        <select class="ql-background"></select>
                                    </span>
                                    <span class="ql-formats">
                                        <button class="ql-script" value="sub"></button>
                                        <button class="ql-script" value="super"></button>
                                    </span>
                                    <span class="ql-formats">
                                        <button class="ql-header" value="1"></button>
                                        <button class="ql-header" value="2"></button>
                                        <button class="ql-blockquote"></button>
                                        <button class="ql-code-block"></button>
                                    </span>
                                    <span class="ql-formats">
                                        <button class="ql-list" value="ordered"></button>
                                        <button class="ql-list" value="bullet"></button>
                                        <button class="ql-indent" value="-1"></button>
                                        <button class="ql-indent" value="+1"></button>
                                    </span>
                                    <span class="ql-formats">
                                        <button class="ql-direction" value="rtl"></button>
                                        <select class="ql-align"></select>
                                    </span>
                                    <span class="ql-formats">
                                        <button class="ql-link"></button>
                                        <button class="ql-image"></button>
                                        <button class="ql-video"></button>
                                        <button class="ql-formula"></button>
                                    </span>
                                    <span class="ql-formats">
                                        <button class="ql-clean"></button>
                                    </span>
                                    <span class="ql-formats">
                                        <button type="button" id="preview-btn" class="btn btn-secondary">Preview HTML</button>
                                    </span>
                                </div>
                                <div id="editor2" style="min-height: 200px;"></div>
                                <div id="preview-container"></div>
                                @error('body')
                                    <span class="invalid-feedback d-block mt-2">{{ $message }}</span>
                                @enderror
                            </div>
                        </div>

                        <div class="col-12 mt-4">
                            <button type="submit" class="btn btn-primary">Create</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@section('js')
<script src="https://code.jquery.com/jquery-3.5.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/xml.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/quill@2.0.3/dist/quill.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        console.log('DOM fully loaded');

        // Initialize toastr options
        toastr.options = {
            closeButton: true,
            progressBar: true,
            positionClass: 'toast-top-right'
        };

        let quill = null;
        try {
            const editorElement = document.querySelector('#editor2');
            if (!editorElement) {
                console.error('Editor element #editor2 not found');
                return;
            }

            // Register highlight.js with Quill for HTML syntax
            hljs.configure({ languages: ['html', 'xml'] });
            quill = new Quill('#editor2', {
                modules: {
                    syntax: {
                        highlight: (text) => hljs.highlight(text, { language: 'html' }).value
                    },
                    toolbar: '#toolbar-container',
                },
                placeholder: 'Enter your HTML or text here...',
                theme: 'snow'
            });
            console.log('Quill initialized successfully');
        } catch (error) {
            console.error('Failed to initialize Quill:', error);
            return;
        }

        const form = document.getElementById('mainForm');
        const bodyTextarea = document.getElementById('body');
        const previewBtn = document.getElementById('preview-btn');
        const previewContainer = document.getElementById('preview-container');
        const editorContainer = document.getElementById('editor2');

        if (!form || !bodyTextarea || !previewBtn || !previewContainer || !editorContainer) {
            console.error('Required elements not found:', {
                form: !!form,
                bodyTextarea: !!bodyTextarea,
                previewBtn: !!previewBtn,
                previewContainer: !!previewContainer,
                editorContainer: !!editorContainer
            });
            return;
        }

        // Function to detect and format URLs and phone numbers
        function applyLinkFormatting(delta) {
            const Delta = window.Quill.import('delta') || function() {
                return { ops: [] };
            };
            const urlRegex = /(https?:\/\/[^\s<]+|www\.[^\s<]+|[^\s<]+\.(com|org|net|au|edu|gov)[^\s<]*)/gi;
            const phoneRegex = /(\+?\d{1,3}[\s-]?\d{3,4}[\s-]?\d{3,4}[\s-]?\d{3,4})/g;

            const plainText = delta.ops.reduce((text, op) => text + (op.insert || ''), '');
            let newDelta = new Delta();

            const lines = plainText.split('\n').filter(line => line.trim() !== '');
            if (lines.length > 0) {
                newDelta.insert(lines[0], { header: 1 });
                newDelta.insert('\n');
                lines.shift();
            }

            lines.forEach((line, index) => {
                if (!line.trim()) {
                    newDelta.insert('\n');
                    return;
                }

                let lastIndex = 0;
                const matches = [];
                let match;

                while ((match = urlRegex.exec(line)) !== null) {
                    matches.push({ index: match.index, text: match[0], type: 'url' });
                }
                urlRegex.lastIndex = 0;
                while ((match = phoneRegex.exec(line)) !== null) {
                    matches.push({ index: match.index, text: match[0], type: 'phone' });
                }
                phoneRegex.lastIndex = 0;
                matches.sort((a, b) => a.index - b.index);

                matches.forEach(match => {
                    if (lastIndex < match.index) {
                        newDelta.insert(line.slice(lastIndex, match.index));
                    }
                    if (match.type === 'url') {
                        const formattedUrl = match.text.startsWith('http') ? match.text : `https://${match.text}`;
                        newDelta.insert(match.text, { link: formattedUrl });
                    } else if (match.type === 'phone') {
                        const cleanPhone = match.text.replace(/[\s-]/g, '');
                        newDelta.insert(match.text, { link: `tel:${cleanPhone}` });
                    }
                    lastIndex = match.index + match.text.length;
                });

                if (lastIndex < line.length) {
                    newDelta.insert(line.slice(lastIndex));
                }

                if (index < lines.length - 1) {
                    newDelta.insert('\n');
                }
            });

            return newDelta;
        }

        // Toggle between editor and preview without form submission
        let isPreviewMode = false;
        previewBtn.addEventListener('click', function(event) {
            event.preventDefault(); // Prevent any form submission
            if (!quill || !quill.root) {
                console.error('Quill is not initialized or root is undefined');
                return;
            }

            isPreviewMode = !isPreviewMode;
            if (isPreviewMode) {
                previewBtn.textContent = 'Back to Editor';
                editorContainer.style.display = 'none';
                previewContainer.style.display = 'block';
                const htmlContent = quill.root.innerHTML;
                previewContainer.innerHTML = htmlContent; // Render HTML as a webpage
                console.log('Preview mode - HTML content:', htmlContent);
            } else {
                previewBtn.textContent = 'Preview HTML';
                editorContainer.style.display = 'block';
                previewContainer.style.display = 'none';
                previewContainer.innerHTML = '';
            }
        });

        // Handle text changes and update textarea
        quill.on('text-change', function() {
            try {
                const currentText = quill.getText();
                if (currentText.match(/(https?:\/\/|www\.|\.(com|org|net|au|edu|gov)|\+?\d{1,3}[\s-]?\d{3,4})/)) {
                    const cursorPosition = quill.getSelection()?.index || 0;
                    const delta = quill.getContents();
                    const newDelta = applyLinkFormatting(delta);
                    quill.setContents(newDelta, 'silent');
                    quill.setSelection(cursorPosition, 0, 'silent');
                }
                bodyTextarea.value = quill.root?.innerHTML || '';
                console.log('Text changed - Formatted content:', quill.root?.innerHTML);
                console.log('Text changed - Textarea value:', bodyTextarea.value);
            } catch (error) {
                console.error('Text change error:', error);
            }
        });

        // Handle form submission
        form.addEventListener('submit', function(event) {
            event.preventDefault();
            console.log('Submit button clicked');
            if (!quill || !quill.root) {
                console.error('Quill is not initialized or root is undefined');
                return;
            }

            try {
                const delta = quill.getContents();
                const formattedContent = applyLinkFormatting(delta);
                quill.setContents(formattedContent, 'silent');
                bodyTextarea.value = quill.root.innerHTML || '';
                console.log('Form submit - Formatted content:', quill.root.innerHTML);
                console.log('Form submit - Textarea value:', bodyTextarea.value);
                const formData = new FormData(form);
                console.log('Form data being sent:', Object.fromEntries(formData));
                form.submit();
            } catch (error) {
                console.error('Form submission error:', error);
            }
        });

        // Initialize editor
        try {
            quill.setContents({ ops: [{ insert: '\n' }] });
            bodyTextarea.value = '';
        } catch (error) {
            console.error('Initial content set error:', error);
        }
    });

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
</script>
<meta name="csrf-token" content="{{ csrf_token() }}">
@endsection
